import type { Rule } from 'eslint'

export default function getShouldReturn(): Rule.RuleModule {
    return {
        meta: {
            type: 'suggestion',
            docs: {
                description: '含有"get"名称的函数必须有返回值',
            },
            schema: [],
            fixable: 'code',
        },
        create(context) {
            return {
                FunctionDeclaration(node) {
                    const functionName = node.id?.name
                    if (!functionName.startsWith('get'))
                        return

                    const blockStatementBody = node.body.body
                    const lastNode = blockStatementBody[blockStatementBody.length - 1]

                    if (!lastNode || lastNode.type !== 'ReturnStatement') {
                        context.report({
                            node,
                            message: `${functionName}函数必须有返回值`,
                            fix(fixer) {
                                const endPoint = node.range![1]
                                return fixer.replaceTextRange([endPoint - 1, endPoint], '\nreturn \"\"\n}')
                            },
                        })
                    }
                },
                ArrowFunctionExpression(node) {
                    const functionName = node.parent.id.name
                    if (!functionName.startsWith('get'))
                        return

                    const blockStatementBody = node.body.body
                    const lastNode = blockStatementBody[blockStatementBody.length - 1]

                    if (!lastNode || lastNode.type !== 'ReturnStatement') {
                        context.report({
                            node,
                            message: `${functionName}函数必须有返回值`,
                            fix(fixer) {
                                const endPoint = node.range![1]
                                return fixer.replaceTextRange([endPoint - 1, endPoint], '\nreturn \"\"\n}')
                            },
                        })
                    }
                },
            }
        },

    }
}
